<template>
  <div class="login-container">
    <!-- 左侧菜单 -->
    <div class="left">
      <!-- 标题部分 -->
      <div class="title-box">
        <img src="@/assets/login_icon.png" alt="" />
        <span class="title">黑马面面</span>
        <span class="line"></span>
        <span class="sub-title">用户登录</span>
      </div>
      <!-- 表单 -->
      <el-form
        class="login-form"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
      >
        <el-form-item prop="phone">
          <el-input
            v-model="ruleForm.phone"
            prefix-icon="el-icon-user"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            prefix-icon="el-icon-lock"
            show-password
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-row>
            <el-col :span="17">
              <el-input
                prefix-icon="el-icon-key"
                v-model="ruleForm.code"
                placeholder="请输入验证码"
              ></el-input>
            </el-col>
            <el-col style="margin-left:10px;" :span="6">
              <img
                @click="changeLoginCaptcha"
                class="captcha"
                :src="loginCaptchaUrl"
                alt=""
              />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="checked">
          <el-checkbox v-model="ruleForm.checked" />
          我已阅读并同意<el-link
            type="primary"
            href="https://element.eleme.io"
            target="_blank"
            >用户协议</el-link
          >和<el-link
            type="primary"
            href="https://element.eleme.io"
            target="_blank"
            >隐私条款</el-link
          >
        </el-form-item>
        <el-form-item>
          <el-button @click="login" style="width:100%" type="primary"
            >登 录</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            @click="dialogVisible = true"
            style="width:100%"
            type="primary"
            >注 册</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 右侧部分 -->
    <div class="right">
      <img src="@/assets/login_bg.png" alt="" />
    </div>
    <!-- 注册部分 -->
    <el-dialog
      class="register-dialog"
      title="用户注册"
      center
      :show-close="false"
      :visible.sync="dialogVisible"
    >
      <el-form
        :model="registerForm"
        :rules="registerRules"
        label-width="70px"
        label-position="left"
        ref="registerFormRef"
      >
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadAvatarUrl"
            :data="uploadImgObj"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="registerForm.avatar"
              :src="`${baseURL}/${registerForm.avatar}`"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="username">
          <el-input v-model="registerForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="registerForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="图形码" prop="vcode">
          <el-row>
            <el-col :span="17">
              <el-input v-model="registerForm.vcode"></el-input>
            </el-col>
            <el-col style="margin-left:10px;" :span="6">
              <img
                @click="changeRegisterCaptcha"
                style="width:100%;height:40px;"
                :src="registerCaptchaUrl"
                alt=""
              />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="验证码" prop="rcode">
          <el-row>
            <el-col :span="17">
              <el-input v-model="registerForm.rcode"></el-input>
            </el-col>
            <el-col style="margin-left:10px;" :span="6">
              <el-button @click="getSms">获取用户验证码</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="register">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { BASE_URL } from '../../utils/url'
import { setToken } from '../../utils/token'
export default {
  name: 'Login',
  data() {
    // 检测用户协议是否勾选上
    var checkAgreement = (rule, value, callback) => {
      if (value === false) {
        return callback(new Error('必须勾选用户协议'))
      }
      callback()
    }
    // 检测手机号
    var checkPhone = (rule, value, callback) => {
      const reg = /^1[3456789][0-9]{9}$/
      if (!reg.test(value)) {
        return callback(new Error('手机号不合法'))
      }
      callback()
    }
    // 检测手验证码
    var checkCode = (rule, value, callback) => {
      const reg = /^[0-9]{4}$/
      if (!reg.test(value)) {
        return callback(new Error('验证码格式不对'))
      }
      callback()
    }
    // 检测邮箱
    var checkEmail = (rule, value, callback) => {
      /* eslint-disable */
      const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (!reg.test(value)) {
        return callback(new Error('邮箱格式不对'))
      }
      callback()
    }
    return {
      baseURL: BASE_URL, // 基准路径
      loginCaptchaUrl: `${BASE_URL}/captcha?type=login`, // 登录验证码
      registerCaptchaUrl: `${BASE_URL}/captcha?type=sendsms`, // 注册验证码
      uploadAvatarUrl: `${BASE_URL}/uploads`, // 头像上传Url
      uploadImgObj: {}, // 头像上传时候的图片对象
      ruleForm: {
        checked: false, // 协议条款是否选中
        phone: '',
        password: '',
        code: ''
      },
      rules: {
        phone: [{ validator: checkPhone, trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        code: [{ validator: checkCode, trigger: 'blur' }],
        checked: [
          {
            validator: checkAgreement,
            trigger: 'change'
          }
        ]
      },
      dialogVisible: false, // 是否显示注册框
      registerForm: {
        username: '', // 用户名
        phone: '', // 手机号
        email: '', // 邮箱
        avatar: null, // 头像
        password: '', // 密码
        rcode: '', // 验证码
        vcode: '' // 图形码
      },
      registerRules: {
        avatar: [{ required: true, message: '请上传头像', trigger: 'blur' }],
        username: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        email: [{ required: true, validator: checkEmail, trigger: 'blur' }],
        phone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        vcode: [{ required: true, message: '输入图形码', trigger: 'blur' }],
        rcode: [{ required: true, message: '输入验证码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    /** 登录相关 */
    changeLoginCaptcha() {
      this.loginCaptchaUrl = `${BASE_URL}/captcha?type=login&random=${Math.random()}`
    },
    login() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          const res = await this.$axios.post('/login', this.ruleForm)

          if (res.data.code === 200) {
            // 提示
            this.$message({
              message: '登录成功~',
              type: 'success'
            })

            // 保存token到本地
            setToken(res.data.data.token)

            // 跳转到后台
            this.$router.push('/layout')
          } else {
            this.$message({
              message: res.data.message,
              type: 'error'
            })
          }
        }
      })
    },
    /** 注册相关  **/
    beforeAvatarUpload(file) {
      this.uploadImgObj.image = file
    },
    handleAvatarSuccess(response) {
      if (response.code === 200) {
        this.registerForm.avatar = response.data.file_path
      } else {
        this.$message.error(response.message)
      }
    },
    // 获取注册时候的图形码
    changeRegisterCaptcha() {
      this.registerCaptchaUrl = `${BASE_URL}/captcha?type=sendsms&t=${Date.now()}`
    },
    // 获取短信验证码
    async getSms() {
      const res = await this.$axios.post('/sendsms', {
        code: this.registerForm.vcode,
        phone: this.registerForm.phone
      })

      if (res.data.code === 200) {
        this.registerForm.rcode = res.data.data.captcha
      } else {
        this.$message.error(res.data.message)
      }
    },
    // 注册
    register() {
      this.$refs.registerFormRef.validate(async valid => {
        if (!valid) return

        const res = await this.$axios.post('/register', this.registerForm)

        if (res.data.code === 200) {
          this.$message({
            message: '注册成功~',
            type: 'success'
          })

          // 关闭
          this.dialogVisible = false

          // 清空内容
          this.registerForm = {
            username: '', // 用户名
            phone: '', // 手机号
            email: '', // 邮箱
            avatar: null, // 头像
            password: '', // 密码
            rcode: '', // 验证码
            vcode: '' // 图形码
          }
        } else {
          this.$message.error(res.data.message)
        }
      })
    }
  }
}
</script>

<style lang="less">
.login-container {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  background: linear-gradient(
    225deg,
    rgba(20, 147, 250, 1),
    rgba(1, 198, 250, 1)
  );
  .left {
    width: 478px;
    height: 550px;
    background: rgba(245, 245, 245, 1);
    padding: 48px;
    .title-box {
      display: flex;
      align-items: center;
      img {
        width: 22px;
        height: 17px;
        margin-right: 16px;
      }
      .title {
        font-size: 24px;
        margin-right: 14px;
      }
      .line {
        width: 1px;
        background-color: #c7c7c7;
        height: 27px;
        margin-right: 12px;
      }
      .sub-title {
        font-size: 22px;
      }
    }
    .login-form {
      margin-top: 29px;
      .captcha {
        width: 100%;
        height: 40px;
      }
    }
    .rule-box {
      .el-checkbox {
        display: flex;
        align-items: center;
        .el-checkbox__label {
          display: flex;
          align-items: center;
        }
      }
    }
    .btn-box {
      .el-button {
        width: 100%;
        margin-left: 0;
        margin-bottom: 28px;
      }
    }
  }
  .register-dialog {
    .el-dialog {
      width: 600px;
    }
    .el-dialog__header {
      background: linear-gradient(
        to left,
        rgba(1, 198, 250, 1),
        rgba(20, 147, 250, 1)
      );
      text-align: center;
      .el-dialog__title {
        color: white;
      }
    }
    .captcha {
      width: 100%;
    }
    .avatar-uploader {
      display: flex;
      justify-content: center;
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
}
</style>
